package BackTracking;

import java.util.*;

/**
 * Lettcode 47: https://leetcode-cn.com/problems/permutations-ii/
 */
public class permuteUnique {
    private int[] nums;

    private int length;

    public static void main(String[] args) {
        int[] input = {1, 1, 2};
        System.out.println(new permuteUnique().permuteUnique(input));
    }

    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return res;
        }
        Arrays.sort(nums);
        this.nums = nums;
        this.length = nums.length;
        boolean[] visited = new boolean[length];
        Set<List<Integer>> tempRes = new HashSet<>();
        List<Integer> curRes = new ArrayList<>();
        backTrackingI(curRes, tempRes, visited);
        res = new ArrayList<>(tempRes);
        return res;
    }

    private void backTracking(List<Integer> curRes, Set<List<Integer>> res, boolean[] visited) {
        if (curRes.size() == length) {
            res.add(new ArrayList<>(curRes));
            return;
        }
        for (int i = 0; i < length; i++) {
            if (visited[i]) {
                continue;
            }
            curRes.add(nums[i]);
            visited[i] = true;
            backTracking(curRes, res, visited);
            curRes.remove(curRes.size() - 1);
            visited[i] = false;
        }
    }

    private void backTrackingI(List<Integer> curRes, Set<List<Integer>> res, boolean[] visited) {
        if (curRes.size() == length) {
            res.add(new ArrayList<>(curRes));
            return;
        }
        for (int i = 0; i < length; i++) {
            if (i!=0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
                continue;
            }
            if (visited[i]) {
                continue;
            }
            curRes.add(nums[i]);
            visited[i] = true;
            backTracking(curRes, res, visited);
            curRes.remove(curRes.size() - 1);
            visited[i] = false;
        }
    }
}
